package com.lagou.config;

import com.lagou.io.Resources;
import com.lagou.pojo.Configuration;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author: xiangfeng
 * @date: 2021年09月28日
 */

public class XMLConfigBuilder {

    private Configuration configuration;
    public XMLConfigBuilder(){
        configuration = new Configuration();
    }

    /**
     * 该方法就是将配置文件（核心配置文件）进行解析，封装Configuration
     * @param inputStream
     * @return
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        /**
         * 读取核心配置文件
         */
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();//根标签对象
        //对数据源进行解析以及获取
        List<Element> list = rootElement.selectNodes("//property");//获取所有的property标签
        Properties properties = new Properties();
        for (Element element : list) {//遍历获取到的property标签
            String name = element.attributeValue("name");//获取property标签的name属性
            String value = element.attributeValue("value");//获取property标签的value属性
            properties.setProperty(name,value);
        }
        /*
         * 设置数据源信息
         */
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(comboPooledDataSource);

        //对mapper.xml进行解析:拿到路径--字节输入流--dom4j进行解析
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            String mapperPath = element.attributeValue("resource");//拿到mapper路径
            InputStream resourcesAsStream = Resources.getResourcesAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourcesAsStream);
        }
        return configuration;
    }

}
